#include "AlarmEvent.h"
#include "SOCK_Acceptor.h"
#include <iostream>
#include <ctime>

using namespace std;

AlarmEvent::AlarmEvent(INET_Addr _addr, Mode m, int pri, char* text) : addr(_addr), priority(pri), textString(text)
{
	stream = SOCK_Stream();

	if(SERVER == m)
	{
		acceptor = SOCK_Acceptor();
		acceptor.open(addr);
		handle.setConnection(acceptor.getHandle());
	}
	else if(CLIENT == m)
	{
		connector = SOCK_Connector();
		connector.connect(addr, stream);
		handle.setConnection(stream.get_handle());
	}
}

AlarmEvent::~AlarmEvent(void)
{

}

void AlarmEvent::handle_event(Handler<SOCKET> handle, Event_Type et)
{
	const size_t len = 50;
	char buf[len];

	if(READ_EVENT == et)
	{
		buf[stream.recv(&buf,len,0)]='\0';

		if(strlen(buf) > 0)
		{
			cout << endl << "AlarmEvent read: Priority->";
		
			for(int i = 0; i < strlen(buf); i++)
			{
				if(buf[i] != ',')
				{
					cout << buf[i];
				}

				else
					cout << " Value->";
			}
			time_t rawtime = time(0);
			tm timeinfo = {};
			errno_t err = localtime_s( &timeinfo,&rawtime );
			cout << " Received at: " 
				 << (timeinfo.tm_hour < 10 ? "0" : "")  << timeinfo.tm_hour << ":"
				 << (timeinfo.tm_min < 10 ? "0" : "") << timeinfo.tm_min << ":"
				 << timeinfo.tm_sec;
			cout << endl << endl;
		}
	}
	else if(WRITE_EVENT == et)
	{
		char valueToSend[50] = {};

		_itoa_s(priority,valueToSend,10);
		int len = strlen(valueToSend);
		valueToSend[len] = ',';
		valueToSend[len+1] = '\0';
		int i = 0;
		for(; i < strlen(textString); i++)
		{
			valueToSend[len+1+i] = textString[i];
		}
		valueToSend[len+i+1] = '\0';

		//Transmitt values
		stream.send(valueToSend,0);
	}
	else if(TIMEOUT_EVENT == et)
	{
		cout << "Timeout has occured in AlarmEvent<SOCKET>" << endl;
	}
	else if(ACCEPT_EVENT == et)
	{
		acceptor.accept(stream);
	}
	else if(INIT_EVENT == et)
	{
		stream.send("",0);
	}
	else   //ERROR
		cout << "Error: AlarmEvent, event_type unknown" << endl;
}



